package com.library.admin.modules.book.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.library.admin.modules.book.entity.Book;
import com.library.admin.modules.book.vo.BookVO;
import com.library.admin.modules.book.bo.BookPage;
import com.library.admin.modules.book.bo.BookInsert;
import com.library.admin.modules.book.bo.BookUpdate;
import com.library.admin.modules.book.mapper.BookMapper;
import com.library.admin.modules.book.struct.BookStructMapper;
import com.library.admin.modules.book.service.BookService;
import com.library.common.enums.StatusEnum;
import com.library.common.exception.BaseException;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import com.library.common.util.PageCovertUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author xyh
 * @Desc 图书表(Book)表服务实现类
 * @Date 2023-10-05 17:27:46
 */

@Log4j2
@Service("bookService")
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Resource
    private BookStructMapper bookStructMapper;
    @Resource
    private BookMapper bookMapper;

    /**
     * 缓存
     * key: bookId
     * value: book
     */
    Map<Integer, Book> bookMap = new LinkedHashMap<>();


    @Override
    public IPage<BookVO> queryByPage(BookPage page) {
        // 查询条件
        LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(page.getAuthor())) {
            queryWrapper.eq(Book::getAuthor, page.getAuthor());
        }
        if (StrUtil.isNotEmpty(page.getName())) {
            queryWrapper.like(Book::getName, page.getName());
        }
        if (page.getBookType() != null) {
            queryWrapper.eq(Book::getBookType, page.getBookType());
        }
        queryWrapper.orderByDesc(Book::getCreateTime);
        queryWrapper.eq(Book::getDelFlag, 0);
        // 查询分页数据
        Page<Book> bookPage = new Page<Book>(page.getCurrent(), page.getSize());
        IPage<Book> pageData = baseMapper.selectPage(bookPage, queryWrapper);

        //转换成vo
        IPage<BookVO> records = PageCovertUtil.pageVoCovert(pageData, BookVO.class);
        return records;
    }

    @Override
    public void init() {
        List<Book> bookList = bookMapper.selectList(new QueryWrapper<>());
        try {
            if (CollUtil.isNotEmpty(bookList)) {
                for (Book book : bookList) {
                    bookMap.put(book.getId(), book);
                }
            }
            log.info("图书添加缓存成功！");
        } catch (Exception e) {
            log.error("图书添加缓存失败！", e);
        }
    }


    @Override
    public BookVO queryById(Integer id) {
        Book book = bookMap.get(id);
        if (book == null) {
            book = baseMapper.selectById(id);
        }
        if (book != null) {
            if (book.getDelFlag() != null && book.getDelFlag().equals((byte) 1)) {
                return null;
            }
        }
        return bookStructMapper.bookToBookVO(book);
    }

    @Override
    public boolean insert(BookInsert bookInsert) {
        Book book = bookStructMapper.insertToBook(bookInsert);
        checkBookName(book);
        save(book);
        bookMap.put(book.getId(), book);
        return true;
    }


    @Override
    public boolean update(BookUpdate bookUpdate) {
        Book book = bookStructMapper.updateToBook(bookUpdate);
        checkBookName(book);
        updateById(book);
        bookMap.put(book.getId(), book);
        return true;
    }

    private void checkBookName(Book book) {
        Book one = lambdaQuery().eq(Book::getIsbn, book.getIsbn())
                .select(Book::getId)
                .last("limit 1")
                .one();
        if (one != null && !one.getId().equals(book.getId())) {
            throw new BaseException("该书籍已经存在，不能重读添加！");
        }
    }

    @Override
    public void deleteById(Integer id) {
        Book book = bookMap.get(id);
        book.setDelFlag((byte) 1);
        updateById(book);
        bookMap.remove(id);
    }

    /**
     * 图书筛选下拉数据展示
     *
     * @return
     */
    @Override
    public List<Book> getBookList() {
        List<Book> bookList = lambdaQuery().select(Book::getId, Book::getName, Book::getIsbn)
                .eq(Book::getBookStatus, StatusEnum.NORMAL).list();
        return bookList;
    }

    @Override
    public boolean updateBookNum(Integer bookId, Integer num, Boolean borrowingOrReturn) {
        Book book = bookMapper.selectById(bookId);
        if (borrowingOrReturn) {
            Integer bookNum = book.getBorrowedQuantity() + num;
            if (book.getQuantity() > bookNum) {
                book.setBorrowedQuantity(book.getBorrowedQuantity() + num);
                log.info("图书借阅数量扣除成功！图书id:{}", bookId);
            } else {
                book.setBookStatus(StatusEnum.STOP.getCode());
                return false;
            }
        } else {
            //被借阅数量-归还的数量
            book.setBorrowedQuantity(book.getBorrowedQuantity() - num);
        }
        updateById(book);
        return true;
    }

}
